package com.bot.rf;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;

import static java.nio.file.StandardWatchEventKinds.*;
import static com.bot.rf.util.MyLogger.LOGGER;
import static com.bot.rf.util.MyLogger.getTrace;
import static com.bot.rf.util.FileUtil.deleteFile;
/**
 * @program: report-form-demo
 * @description: rfid文件夹监听服务
 * @author: zyy
 * @create: 2021-02-25 14:18
 **/
public class WatchFilePath extends Thread {

    /**
     * 传输结束标志
     */
    private static final String END_FILE = "end";

    /**
     * 监听路径
     */
    private static String PATH;

    /**
     * 是否为结果文件
     */
    private boolean isRes = false;

    /**
     * 监听服务
     */
    private WatchService watcher;

    /**
     * Constructs
     *
     * @param path 监听路径
     * @throws IOException IO异常
     */
    public WatchFilePath(Path path) throws IOException {
        PATH = path.toString();
        watcher = FileSystems.getDefault().newWatchService();
        path.register(watcher, ENTRY_DELETE, ENTRY_CREATE, ENTRY_MODIFY);
    }

    /**
     * Method description
     *
     * @throws InterruptedException
     */
    public void handleEvents(Boolean needReport) throws InterruptedException {
        String resFile = "", floor = "";
        LOGGER.info("正在监听文件夹：" + PATH);
        // 删除结束标志文件
        deleteFile(PATH + File.separator + END_FILE);
        while (true) {
            WatchKey key = watcher.take();
            String fileName = "";
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind kind = event.kind();
                // 事件可能lost or discarded
                if (kind == OVERFLOW) {
                    continue;
                }
                WatchEvent<Path> e = (WatchEvent<Path>) event;
                fileName = e.context().toString();
                String entryCreate = "ENTRY_CREATE";
                if (entryCreate.equals(kind.name())) {
                    if (fileName.matches(".*\\.res$")) {
                        // 监听到结果文件创建
                        resFile = PATH + File.separator + fileName;
                        floor = fileName.substring(0, 2);
                        isRes = true;
                        LOGGER.info("检测到res文件:" + fileName + "，等待传输完成...");
                    }
                }
            }
            if (!key.reset()) {
                break;
            }
            File[] files = new File(PATH).listFiles();
            for (File file : files) {
                if (file.getName().equals(END_FILE)) {
                    // 监听到结束标志文件创建
                    LOGGER.info("检测到end文件，等待解析...");
                    Thread.sleep(100);
                    // 删除结束标志文件
                    deleteFile(PATH + File.separator + END_FILE);
                    Res2Database res2Database = new Res2Database(resFile);
                    resFile = "";
                    isRes = false;
                    if (!needReport) {
                        GenerateReport.rfResProcessCallback(floor, res2Database.getReportPath(),
                                res2Database.getResBookMap(),res2Database.getAbnormalBookNums());
                    }
                    LOGGER.info("正在监听...");
                }
            }
        }
    }

    @Override
    public void run()
    {
        try {
            handleEvents(false);
        } catch (InterruptedException e) {
            LOGGER.error(getTrace(e));
        }
    }
}
